const router = require('express').Router();
const mongoose = require('mongoose');
const DictionaryModel = mongoose.models['Dictionary'];

router.post('/add', async function (req, res, next) {
    try{
        await DictionaryModel.create({
            key:req.body.key,
            value:req.body.value
        });
        res.data(true);
    }catch(e){
        next(e.message);
    }
});

router.post('/edit', async function (req, res, next) {
    try{
        await DictionaryModel.update({_id:req.body._id},{$set: {
            key:req.body.key,
            value:req.body.value
        }}).exec();
        res.data(true);
    }catch(e){
        next(e.message);
    }
});

router.get('/get', async function (req, res, next) {
    try{
        let data=await DictionaryModel.findOne({key:req.query.key});
        res.data(data.value);
    }catch(e){
        next(e.message);
    }
});

router.get('/getJSON', async function (req, res, next) {
    try{
        let data=await DictionaryModel.findOne({key:req.query.key});
        res.data(JSON.parse(data.value));
    }catch(e){
        next(e.message);
    }
});

router.get('/remove', async function (req, res, next) {
    try{
        if(!!req.query._id){
            await DictionaryModel.remove({_id:req.query._id});
        }
        res.data(true);
    }catch(e){
        next(e.message);
    }
});


router.get('/list', async function (req, res, next) {
    try{
        let data=await DictionaryModel.find({}).sort({_id:-1});
        res.data(data);
    }catch(e){
        next(e.message);
    }
});
module.exports = router;